/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Xceed.Silverlight.Data;

namespace Xceed.Silverlight.ListBox
{
  internal class SelectedItemsAsyncResult : IAsyncResult
  {
    internal SelectedItemsAsyncResult( IEnumerable<SelectionRange> selectionRanges, AsyncCallback asyncCallback, object asyncState, DataSourceWrapper dataSource )
    {
      if( selectionRanges == null )
        throw new ArgumentNullException( "selectionRanges" );

      if( asyncCallback == null )
        throw new ArgumentNullException( "asyncCallback" );

      if( dataSource == null )
        throw new ArgumentNullException( "dataSource" );

      this.AsyncState = asyncState;
      this.AsyncCallback = asyncCallback;

      this.SelectedItems = new List<object>();

      this.IsCompleted = false;
      this.CompletedSynchronously = true;

      m_enumerator = dataSource.GetDataRangeEnumerator( this.GetDataRangeEnumerator( selectionRanges ) );
      m_enumerator.Reset();
    }

    internal List<object> SelectedItems
    {
      get;
      private set;
    }

    internal AsyncCallback AsyncCallback
    {
      get;
      private set;
    }

    internal void Launch()
    {
      this.WorkerMethod( null );
    }

    private void WorkerMethod( IAsyncResult asyncResult )
    {
      bool isAsyncCallback = false;

      //If this method was involed as the async callback for a BeginMoveNext
      if( asyncResult != null )
      {
        //If the call was completed synchronously, destack, processing will be done in calling stack frame.
        if( asyncResult.CompletedSynchronously )
          return;

        if( !asyncResult.IsCompleted )
          throw new ListBoxInternalException(); //AsyncCallback was called, but IAsyncResult indicates it has not completed.

        isAsyncCallback = true;
      }

      bool completedSynchronously = true;
      bool moveNextSucceeded = true;
      do
      {
        //If there is already a IAsyncResult, then we do not call another moveNext
        if( !isAsyncCallback )
        {
          asyncResult = m_enumerator.BeginGetNext( new AsyncCallback( WorkerMethod ), null );
        }

        if( asyncResult.IsCompleted )
        {
          GetNextResult result = m_enumerator.EndGetNext( asyncResult );
          moveNextSucceeded = result.Success;

          if( moveNextSucceeded )
          {
            this.SelectedItems.Add( result.Item.LastChild.Data );
          }
        }
        else
        {
          Debug.Assert( !isAsyncCallback );

          completedSynchronously = false;
        }

        //reset the flag to enable another iteration of the loop.
        isAsyncCallback = false;
      }
      while( completedSynchronously && moveNextSucceeded );

      if( !completedSynchronously )
      {
        this.CompletedSynchronously = false;
      }

      if( !moveNextSucceeded )
      {
        this.IsCompleted = true;
        this.AsyncCallback.Invoke( this );
      }

    }

    private IEnumerable<DataRange> GetDataRangeEnumerator( IEnumerable<SelectionRange> selectionRanges )
    {
      foreach( SelectionRange selectionRange in selectionRanges )
      {
        yield return this.ConvertSelectionRange( selectionRange );
      }
    }

    private DataRange ConvertSelectionRange( SelectionRange selectionRange )
    {
      DataRangeContext dataRangeContext = selectionRange.DataRangeContext;

      if( selectionRange.SelectToEnd )
      {
        if( selectionRange.SelectFromStart )
        {
          return DataRange.All( true, dataRangeContext );
        }
        else
        {
          return DataRange.From( true, selectionRange.StartRangeInfos, selectionRange.StartRangeInfos.IsInclusive, dataRangeContext );
        }
      }
      else if( selectionRange.SelectFromStart )
      {
        return DataRange.To( true, selectionRange.EndRangeInfos, selectionRange.EndRangeInfos.IsInclusive, dataRangeContext );
      }
      else
      {
        return DataRange.From( true, selectionRange.StartRangeInfos, selectionRange.StartRangeInfos.IsInclusive, selectionRange.EndRangeInfos, selectionRange.EndRangeInfos.IsInclusive, dataRangeContext );
      }
    }

    #region IAsyncResult Members

    public object AsyncState
    {
      get;
      private set;
    }

    public WaitHandle AsyncWaitHandle
    {
      get
      {
        if( m_waitHandle == null )
        {
          m_waitHandle = new ManualResetEvent( false );
        }

        return m_waitHandle;
      }
    }

    public bool CompletedSynchronously
    {
      get;
      private set;
    }

    public bool IsCompleted
    {
      get
      {
        return m_isCompleted;
      }
      private set
      {
        if( value != m_isCompleted )
        {
          m_isCompleted = value;

          if( value && ( m_waitHandle != null ) )
          {
            m_waitHandle.Set();
          }
        }
      }
    }

    #endregion

    private IDataRangeEnumerator m_enumerator;
    private ManualResetEvent m_waitHandle;//null
    private bool m_isCompleted;//false
  }
}
